package cn.heygod.airsql.executor.jdbc;


import cn.heygod.airsql.meta.ColumnMetadata;
import cn.heygod.airsql.meta.TableMetadata;
import cn.heygod.airsql.meta.TableMetadataService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ReflectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Set;

/**
 * @className: JdbcRowMapper
 * @author: Simon
 * @description: TODO
 * @date: 2024/1/26 23:41
 * @version: 1.0
 */
public class JdbcRowMapper<T> implements RowMapper<T> {

    private Logger log = LoggerFactory.getLogger(getClass());

    private Class<T> modelClass = null;

    public JdbcRowMapper(Class<T> modelClass){
        this.modelClass = modelClass;
    }

    @Override
    public T mapRow(ResultSet rs, int rowNum) throws SQLException {
        log.info("running mapRow method for {}",modelClass);
        T model = ReflectUtil.newInstance(modelClass);
        TableMetadataService service = TableMetadataService.me();
        TableMetadata meta = service.getTableMetadata(modelClass);
        Set<ColumnMetadata> colMetas = meta.getColumnsMetas();
        for (ColumnMetadata colMeta : colMetas) {
            //通过column得到Value
            Object value = rs.getObject(colMeta.getColumnName());
            BeanUtil.setFieldValue(model,colMeta.getFieldName(),value);
        }
        return model;
    }
}
